# -*- coding: utf-8 -*-
# @Date    : 2024/2/3
# @Author  : zouy
# @Email: 874112501@qq.com
"""https://www.geetest.com/adaptive-captcha-demo"""
import os
import re
import uuid
import time
from urllib.parse import urljoin
import random

import requests
import parsel
from loguru import logger
import execjs

from util import call_back_param, get_jsonp, download_img, DIR_PATH
from gap import get_gap

ss = requests.session()

ss.headers = {
    "Accept": "*/*",
    # "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "zh-CN,zh;q=0.9",
    "referer": "https://www.geetest.com/adaptive-captcha",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
}

# 1. 请求验证码首页，获取link标签中的js网址
index_url = "https://www.geetest.com/adaptive-captcha-demo"
response = ss.get(index_url)
sel = parsel.Selector(response.text)
captcha_demo_link = sel.xpath('//link[contains(@href, "adaptive-captcha-demo.js")]/@href').get()
captcha_demo_url = urljoin(index_url, captcha_demo_link)
# https://www.geetest.com/_next/static/yGLsUSoSGNFNvVZFXHBOL/pages/adaptive-captcha-demo.js
logger.info(f'1.请求首页：{captcha_demo_url}')

# 2.请求第一步的js网址， 提取captchaId
headers = {'referer': 'https://www.geetest.com/adaptive-captcha-demo'}
response = ss.get(captcha_demo_url, headers=headers)
resp_text = response.text
captcha_id = re.search(r'captchaId:\s*"(.*?)",', resp_text).group(1)
logger.info(f'2.获取captchaId: {captcha_id}')  # 同平台captchaId固定：24f56dc13c40dc4a02fd0318567caef5
# time.sleep(2)

# 3. 请求获取验证码相关信息
challenge = str(uuid.uuid4())
params = {
    "callback": call_back_param(),
    "captcha_id": captcha_id,
    "challenge": challenge,
    "client_type": "web",
    "risk_type": "slide",  # ai
    "lang": "zh"
}
ss.headers.update({'referer': "https://www.geetest.com/", 'host': "gcaptcha4.geetest.com"})
load_url = "https://gcaptcha4.geetest.com/load"
response = ss.get(load_url, params=params)
resp_json = get_jsonp(response.text)
# print(resp_json)
json_data = resp_json['data']

load_lot_number = json_data['lot_number']  # '7a559190e40a45ff994a9cd26e54e6bb'
load_payload = json_data['payload']  # '_b-sD20eax9oEJvmoMxvFFW...'
load_process_token = json_data['process_token']  # '9aa7741f1afa76b8955a7490af2bbb7783514f8a772ceaf68caa5e604ad26867'
pow_detail = json_data['pow_detail']  # 'md5'

# 4 下载验证码图片 (https://static.geetest.com/captcha_v4/e70fbf1d77/slide/4b268eea89/2022-04-21T09/bg/dce83aec8b994d928f06519b0bad4946.png)
static_url = 'https://static.geetest.com/'
bg_path = download_img('bg.png', url=urljoin(static_url, json_data['bg']))
slice_path = download_img('slice.png', url=urljoin(static_url, json_data['slice']))
time.sleep(3)

# 5. 计算缺口距离和生成轨迹
distance = get_gap('pic/slice.png', bg_path='pic/bg.png') -15
logger.info(f"缺口距离：{distance}")
# track = get_track(distance)

# 6. 提交参数进行验证
verify_url = "https://gcaptcha4.geetest.com/verify"
with open(os.path.join(DIR_PATH, 'w4.js'), 'r', encoding='utf-8') as f:
    js_code = f.read()

ctx = execjs.compile(js_code)

# passtime = track[-1][-1]  # 拖动时间
passtime = random.randint(500, 1000)  # 拖动时间
logger.info(f'{captcha_id, load_lot_number, distance, passtime, pow_detail}')
w = ctx.call('genSlideW4', captcha_id, load_lot_number, distance, passtime, pow_detail)

logger.info(f'w值：{w}')
params = {
    "callback": call_back_param(),
    "captcha_id": captcha_id,
    "client_type": "web",
    "lot_number": load_lot_number,
    "risk_type": "slide",
    "payload": load_payload,
    "process_token": load_process_token,
    "payload_protocol": "1",
    "pt": "1",
    "w": w
}
time.sleep(1)
response = ss.get(verify_url, params=params)
resp_json = get_jsonp(response.text)
print()
logger.info(resp_json)
